package com.okyai.cms.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.okyai.cms.domain.CmsApp;
import com.okyai.cms.vo.TemplateFileVo;
import com.okyai.common.annotation.Log;
import com.okyai.common.config.Global;
import com.okyai.common.core.controller.BaseController;
import com.okyai.common.core.domain.AjaxResult;
import com.okyai.common.core.page.TableDataInfo;
import com.okyai.common.enums.BusinessType;
import com.okyai.common.utils.StringUtils;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;

@Controller
@RequestMapping("/cms/template")
public class CmsTemplateController  extends BaseController{
	
	private static String TEMPLATE = "templates";
	
	private String prefix = "cms/template";
	
	@RequiresPermissions("cms:template:view")
    @GetMapping()
    public String template()
    {
        return prefix + "/list";
    }
	
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(TemplateFileVo templateFile) {

		String skinFolderName = templateFile.getUrl();	
		
		List<TemplateFileVo> folderlist = new ArrayList<>();
		List<TemplateFileVo> filelist = new ArrayList<>();
		
		File files[] = new File(getRealTemplatePath( skinFolderName)).listFiles();

		if(StringUtils.isNotBlank(skinFolderName)) {
			TemplateFileVo vo = new TemplateFileVo();
			vo.setName("...");
			vo.setType("目录");
			if(skinFolderName.contains(File.separator)) {
				vo.setUrl(skinFolderName.substring(0,skinFolderName.lastIndexOf(File.separator)));
			}else {
				vo.setUrl("");
			}
			
			folderlist.add(vo);
		}
		
		if (files != null) {
			
			for (int i = 0; i < files.length; i++) {
				File currFile = files[i];
				String temp = currFile.getPath();
				//以当前系统分隔符作判断，将不是当前系统的分隔符替换为当前系统的
				temp=temp.replace(File.separator.equals("\\")?"/":"\\", File.separator).replace(getRealTemplatePath(""), "");
				
				TemplateFileVo vo = new TemplateFileVo();
				vo.setUrl(temp);
				vo.setName(temp.substring(temp.lastIndexOf(File.separator)+1));
				if (currFile.isDirectory()) {
					vo.setType("目录");
					folderlist.add(vo);
				} else {
					String suffix = temp.substring(temp.lastIndexOf(".") + 1);
					if(suffix.equalsIgnoreCase("jpg")||suffix.equalsIgnoreCase("gif")||suffix.equalsIgnoreCase("png")||suffix.equalsIgnoreCase("jpeg")) {
						vo.setType("图片");
					}else {
						vo.setType("文件");
					}
					filelist.add(vo);
				}
			}
			folderlist.addAll(filelist);
		}

		return getDataTable(folderlist);
	}
	
	
	@GetMapping("/edit/{url:.+}")
	public String edit(@PathVariable("url") String url,ModelMap mmap) {
		TemplateFileVo templateFile = new TemplateFileVo();
		if (StringUtils.isNotEmpty(url)) {
		
			try {
				url = URLDecoder.decode(url,FileWriter.DEFAULT_CHARSET.name());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
			templateFile.setContent(FileReader.create(new File(getRealTemplatePath(url))).readString());
			templateFile.setUrl(url);
		}
		mmap.addAttribute("file", templateFile);
		return prefix + "/edit";
	}
	
	@RequiresPermissions("cms:app:edit")
    @Log(title = "网站管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TemplateFileVo templateFile)
    {
		FileWriter.create(new File(getRealTemplatePath(templateFile.getUrl())), FileWriter.DEFAULT_CHARSET)
		.write(templateFile.getContent());
        return toAjax(true);
    }
	
	@GetMapping("/getTemplate")
	@ResponseBody
	public List<String> getTemplate(){
		List<String> list = new ArrayList<>();
		File file = new File(getRealTemplatePath(""));
		String[] str = file.list();
		if (str != null) {
			for (int i = 0; i < str.length; i++) {
				// 避免不为文件夹的文件显示
				if (str[i].indexOf(".") < 0) {
					list.add(str[i]);
				}
			}
		}
		return list;
	}
	
	/**
	 * 获取模板上传路径
	 * @param skinFolderName
	 * @return
	 */
	private String getRealTemplatePath(String skinFolderName) {
		String url = Global.getProfile()+File.separator+TEMPLATE;
		if(StringUtils.isNotBlank(skinFolderName)) {
			url+= skinFolderName;
		}
		return url;
	}
}
